#!/bin/sh /etc/rc.common

USE_PROCD=1
START=92

append_arg() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get val "$cfg" "$var"
	[ -n "$val" -o -n "$def" ] && procd_append_param command $opt "${val:-$def}"
}

append_bool() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get_bool val "$cfg" "$var" "$def"
	[ "$val" = 1 ] && procd_append_param command "$opt"
}

start_instance() {
	local cfg="$1"
	local aux
	local satip servers

	config_get_bool aux "$cfg" 'disabled' '0'
	[ "$aux" = 1 ] && return 1

	procd_open_instance

	procd_set_param command /usr/sbin/minisatip
	procd_append_param command "-f -R /usr/share/minisatip/html"

	append_arg "$cfg" adapter_buffers "-b"
	append_arg "$cfg" delsys "-Y"
	append_arg "$cfg" diseqc "-d"
	append_arg "$cfg" diseqc_timing "-q"
	append_arg "$cfg" dvbapi_url "-o"
	append_arg "$cfg" dvr_priority "-i"
	append_arg "$cfg" enabled_adapters "-e"
	append_arg "$cfg" http_port "-x"
	append_arg "$cfg" jess_string "-j"
	append_arg "$cfg" lnb "-L"
	append_arg "$cfg" mac_address "-m"
	append_arg "$cfg" no_power_management "-Z"
	append_arg "$cfg" playlist_url "-p"
	append_arg "$cfg" remote_rtp_host "-r"
	append_arg "$cfg" rtsp_port "-y"
	append_arg "$cfg" server_id "-D"
	append_arg "$cfg" simulate_fontends "-a"
	append_arg "$cfg" slave_adapters "-S"
	append_arg "$cfg" socket_write_buffer "-B"
	append_arg "$cfg" udp_port "-P"
	append_arg "$cfg" unicable_string "-u"
	append_arg "$cfg" xml_path "-X"
	append_arg "$cfg" xml_url "-w"

	append_bool "$cfg" clean_psi "-t"
	append_bool "$cfg" satip_tcp "-O"
	append_bool "$cfg" send_encrypted "-E"
	append_bool "$cfg" threads "-T"

	config_get servers "$cfg" satip_servers
	for satip in $servers; do
		procd_append_param command -s "$satip"
	done

	config_get_bool aux "$cfg" 'respawn' '0'
	[ "$aux" = 1 ] && procd_set_param respawn

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "minisatip"
}

start_service() {
	config_load minisatip
	config_foreach start_instance minisatip
}
